/*
 * Copyright(c) 2024 长沙市希尚网络科技有限公司
 * 注意：本内容仅限于长沙市希尚网络科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */

package org.example.security.core;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 *  springsecurity 配置
 *
 * @author liuy
 * @version 1.0 2024/11/14 0014
 */
@Configuration
@EnableWebSecurity(debug = true)
@RequiredArgsConstructor
public class SecurityConfig  {

    private final TokenPreFilter tokenPreFilter;
    @Bean
    public BCryptPasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/public/login.html").permitAll()
                // .requestMatchers("/test/index").permitAll()
//                     .requestMatchers("/test/index").permitAll()

                    .requestMatchers("/static/js/**").permitAll()
                .requestMatchers("/auth/login").permitAll()
                .anyRequest().authenticated()
            )
            .addFilterBefore(tokenPreFilter, UsernamePasswordAuthenticationFilter.class)
            .formLogin(form -> form
               .loginPage("/public/login.html")
 // .authenticationDetailsSource()
//                .usernameParameter("username")
//                .passwordParameter("password")
//                .loginProcessingUrl("/auth/login")
                .permitAll()
            )
                .csrf(csrf->{
                    csrf.disable();
                })
            .logout(logout -> logout.permitAll()
            );

        return http.build();
    }
     @Bean
     public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
         return authenticationConfiguration.getAuthenticationManager();
     }


    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        System.out.println(encoder.encode("123456"));
    }
}
